﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using c_work.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Work.Models;
using Work.util;

namespace Work.Controllers
{
	[Route("[Controller]/[Action]")]
	[ApiController]
	public class UsersController : ControllerBase
	{
		[HttpGet]
		public ActionResult<IEnumerable<string>> test()
		{
			return new string[] { "value1", "value2" };
		}
		private readonly DBContext _context;

		/// <summary>
		/// 查询全部信息
		/// </summary>
		/// <param name="queryInfo"></param>
		/// <returns></returns>
		[HttpPost]
		public String getUserList(QueryInfo queryInfo)
		{
			var d = from i in _context.Users
					select i;
			var data = d.Skip((queryInfo.pageNum - 1) * queryInfo.pageSize)
				.Take(queryInfo.pageSize)
				.Where(s => s.Email.Contains(queryInfo.query));
			Dictionary<String, Object> res = new Dictionary<String, Object>();
			res.Add("data", data);
			res.Add("total", d.ToList().Count);
			res.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(res);
		}

		public UsersController(DBContext context)
		{
			_context = context;
		}

		/// <summary>
		/// 登录
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		[HttpPost]
		[NoSign]
		public string Login([FromBody] User user)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			string flag = "error";
			var u = from i in _context.Users
					where i.Email.Equals(user.Email)
					select new
					{
						i.Email,
						i.Salt,
						i.Hashed,
						i.PermissionId
					};
			try
			{
				var pp = u.ToList()[0].Salt;
				string Hashed = PasswordHasher.Hashed(user.Psd, pp);
				if (u.ToList()[0].Hashed == Hashed)
				{
					flag = "success";
					dic.Add("flag", flag);
					dic.Add("code", 0);
					dic.Add("msg", "登录成功");
					dic.Add("data", u.ToList());
					var userJson = JsonSerializer.Serialize(u);
					HttpContext.Session.SetString("user", userJson);
					return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
				}
				else
					dic.Add("msg", "账号或密码错误");
			}
			catch (Exception e)
			{
				dic.Add("flag", flag);
				dic.Add("msg", e.ToString());
				return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
			}
			dic.Add("flag", flag);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 获取用户信息
		/// </summary>
		/// <param name="Id"></param>
		/// <returns></returns>
		[HttpGet]
		public async Task<string> GetUser(long Id)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var user = await _context.Users.FindAsync(Id);
			if (user == null)
			{
				dic.Add("flag", "error");
				dic.Add("msg", "没有该用户");
				return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
			}
			dic.Add("data", user);
			dic.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 修改用户权限
		/// </summary>
		/// <param name="Id"></param>
		/// <param name="PermissionId"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<string> EditPermission(long Id, int PermissionId)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var user = await _context.Users.FindAsync(Id);
			user.PermissionId = PermissionId;
			_context.Entry(user).State = EntityState.Modified;
			try
			{
				await _context.SaveChangesAsync();
			}
			catch (DbUpdateConcurrencyException e)
			{
				dic.Add("flag", "error");
				dic.Add("msg", e);
				return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
			}
			dic.Add("flag", "success");
			dic.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 修改用户密码
		/// </summary>
		/// <param name="id"></param>
		/// <param name="user"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<string> PutUser(Password psd)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var user = await _context.Users.FindAsync(psd.Id);
			string Hashed = PasswordHasher.Hashed(psd.OriginalPsd, user.Salt);
			if (Hashed == user.Hashed)
			{
				byte[] salt = PasswordHasher.salt();
				string NewHashed = PasswordHasher.Hashed(psd.NewPsd, salt);
				user.Salt = salt;
				user.Hashed = NewHashed;
				_context.Entry(user).State = EntityState.Modified;
				try
				{
					await _context.SaveChangesAsync();
				}
				catch (DbUpdateConcurrencyException)
				{
					if (!UserExists(user.Id))
					{
						dic.Add("flag", "error");
						dic.Add("code", 500);
						dic.Add("msg", "账号不存在");
						return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
					}
					else
					{
						throw;
					}
				}
				dic.Add("flag", "success");
				dic.Add("code", 0);
				dic.Add("msg", "修改成功");
				return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
			}
			dic.Add("flag", "error");
			dic.Add("code", 415);
			dic.Add("msg", "原密码输入错误！！！");
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 用户注册
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		[HttpPost]
		[NoSign]
		public async Task<string> PostUser(User user)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var u = from i in _context.Users
					where i.Email.Equals(user.Email)
					select i;
			if (u.ToList().Count != 0)
			{
				dic.Add("flag", "error");
				dic.Add("code", 500);
				dic.Add("msg", "用户已经注册");
				return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
			}
			///使用 PBKDF2 算法对密码进行哈希处理
			byte[] salt = PasswordHasher.salt();
			string passd = user.Psd.ToString();
			string Hashed = PasswordHasher.Hashed(passd, salt);
			User us = new User()
			{
				Email = user.Email,
				Salt = salt,
				Hashed = Hashed,
				PermissionId = 1,
				Psd = DateTime.Now.Date.ToString("yyyy-MM-dd")
			};
			try
			{
				_context.Users.Add(us);
				await _context.SaveChangesAsync();
			}
			catch (Exception e)
			{
				dic.Add("flag", "error");
				dic.Add("code", 415);
				dic.Add("msg", "抛出异常" + e);
			}
			dic.Add("flag", "success");
			dic.Add("code", 0);
			dic.Add("msg", "用户注册成功");
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 删除用户
		/// </summary>
		/// <param name="Id"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<string> DeleteUser(long Id)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var user = await _context.Users.FindAsync(Id);
			if (user == null)
			{
				dic.Add("msg", "删除失败");
				dic.Add("code", 500);
				return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
			}
			_context.Users.Remove(user);
			await _context.SaveChangesAsync();
			dic.Add("msg", "删除成功");
			dic.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		private bool UserExists(long id)
		{
			return _context.Users.Any(e => e.Id == id);
		}
	}
}
